﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Project.Core.Config.Common.Lang;
using Project.Core.Config.Entity.Dto;

namespace Project.Core.Config.Common.Filter {
    public class ExceptionFilter : IExceptionFilter {

        private readonly ILogger _logger;

        public ExceptionFilter(ILogger<ExceptionFilter> logger) {
            this._logger = logger;
        }

        public void OnException(ExceptionContext context) {
            Exception ex = context.Exception;
            string errMsg = ex.Message;

            _logger.LogError($"发生了一个异常错误。异常信息：{errMsg}");

            //针对不同的自定义异常，做不同处理
            if (context.Exception.GetType() == typeof(UserLoginException)) {
                Result result = Result.Fail(10000, errMsg, null);
                context.Result = new JsonResult(result);
                context.ExceptionHandled = true;
            } else if (context.Exception.GetType() == typeof(ArgumentOutOfRangeException)) {
                Result result = Result.Fail(20000, "信息不存在！", null);
                context.Result = new JsonResult(result);
                context.ExceptionHandled = true;
            } else if (context.Exception.GetType() == typeof(DbUpdateException)) {
                Result result = Result.Fail(30000, "创建失败！", null);
                context.Result = new JsonResult(result);
                context.ExceptionHandled = true;
            } else if (context.Exception.GetType() == typeof(FormatException)) {
                Result result = Result.Fail(40000, errMsg, null);
                context.Result = new JsonResult(result);
                context.ExceptionHandled = true;
            } else if (context.Exception.GetType() == typeof(IOException)) {
                Result result = Result.Fail(50000, errMsg, null);
                context.Result = new JsonResult(result);
                context.ExceptionHandled = true;
            } else {
                Result result = Result.Fail(99999, "操作有误！", null);
                context.Result = new JsonResult(result);
                context.ExceptionHandled = true;
            }
        }
    }

    public class UserLoginException : Exception {
        public string Msg { get; set; }

        public UserLoginException(string msg) {
            this.Msg = msg;
        }
        public override string Message { get { return Msg; } }
    }
}
